/**
 * 
 */
package weightmanager;

import java.io.IOException;
import java.net.UnknownHostException;
import java.util.LinkedList;

import database.DALException;

/**
 * @author Lasse Poulsen
 * 
 */
public class Manager {

	private LinkedList<Thread> threads = new LinkedList<Thread>();

	public Manager(String[] args) throws DALException {
		if (args.length < 1) {
			System.err
					.println("Error, pleace give server:port parameters on commandline!");
			return;
		}
		for (int i = 0; i < args.length; i++) {
			if (args[i].contains(":")) {
				int port;
				String host = "";
				// A bit of replacement to support IPv6's :: hex-annotation.
				String parts[] = args[i].split(":");
				if (parts.length > 2) {
					try {
						port = Integer.parseInt(parts[parts.length - 1]);
						for (int j = 0; j < parts.length - 1; j++) {
							if (j == 0)
								host += parts[j];
							else
								host += ":" + parts[j];
						}
					} catch (NumberFormatException e) {
						int param = i + 1;
						System.err
								.println("Unable to parse parameter " + param);
						return;
					}
				} else if (parts.length < 2) {
					int param = i + 1;
					System.err.println("Error parsing argument " + param);
					break;
				} else {

					try {
						port = Integer.parseInt(parts[1]);
					} catch (NumberFormatException e) {
						int param = i + 1;
						System.err
								.println("Unable to parse parameter " + param);
						break;
					}
				}
				try {
					Client cl = new Client(host, port);
					Thread th = new Thread(cl);
					threads.add(th);
					th.start();
				} catch (UnknownHostException e) {
					System.err.println("Unknown host given: " + e.getMessage());
					break;
				} catch (IOException e) {
					System.err.println("Error creating socket: "
							+ e.getMessage());
					break;
				}
			}
		}

	}

	/**
	 * @param args
	 *            host_1:port_1 host_2:port_2 ... host_n:port_n
	 */
	public static void main(String[] args) {
		try {
			new Manager(args);
		} catch (DALException e) {
			System.err
					.println("It seems like there is no connection to the database or the priviledges for the database is wrong, make sure that the database is running.");
		}
	}

}
